// 发布装饰器
const publish = (event: string) => {
	return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
		const originalMethod = descriptor.value;
		descriptor.value = function (...args: any[]) {
			const result = originalMethod.apply(this, args);
			PubSub.publish(event, result);
			return result;
		};
		return descriptor;
	};
};

export { publish };

class PubSub {
	private static instance: PubSub | null;

	static getInstance(): PubSub {
		// 判断系统是否已经有这个单例
		if (PubSub.instance === null) {
			PubSub.instance = new PubSub();
		}
		return PubSub.instance;
	}

	private static subscribers: { [event: string]: ((data: any) => void)[] } = {};

	public static subscribe(event: string, callback: (data: any) => void): void {
		if (!this.subscribers[event]) {
			this.subscribers[event] = [];
		}
		this.subscribers[event].push(callback);
	}

	public static publish(event: string, data: any): void {
		if (this.subscribers[event]) {
			this.subscribers[event].forEach(callback => callback(data));
		}
	}

	public static unsubscribe(event: string): void {
		if (this.subscribers[event]) {
			this.subscribers[event] = [];
		}
	}
}

export default PubSub;
